<template>
	<!-- 运营系统-短剧列表 -->
	<d2-container class="d-flex flex-column">
		<template v-if="$hasPermission('playlet:playlet:index')">
			<div class="d-flex j-sb" slot="header">
				<el-form class="d-flex b-s mt-2 mb-10" :inline="true" size="small" :model="dataForm"
					@keyup.enter.native="getTableList(true)" @submit.native.prevent>
					<el-form-item label="短剧名称">
						<el-input v-model="dataForm.keyword" placeholder="短剧名称" clearable />
					</el-form-item>
					<el-form-item>
						<el-button icon="el-icon-search" type="primary"
							@click="getTableList(true)">查询</el-button>
					</el-form-item>
					<el-form-item>
						<el-button type="success" icon="el-icon-circle-plus-outline" v-show="$hasPermission('playlet:playlet:create')"
							@click="addOrUpdateData()">添加短剧</el-button>
					</el-form-item>

					<!-- <el-form-item>
						<el-button type="success" icon="el-icon-circle-plus-outline" v-show="$hasPermission('playlet:playlet:mergePlaylet')"
							@click="mergeList()">合并短剧</el-button>
					</el-form-item> -->
					
					<el-form-item>
						<el-button type="success" icon="el-icon-c-scale-to-original" v-show="$hasPermission('playlet:playlet:mergePlaylet')"
						
							@click="mergeList()">合并短剧</el-button>
					</el-form-item>
				</el-form>
				<div class="d-flex">
					<vxe-toolbar ref="toolbarRef" custom :refresh="{ queryMethod: getTableList,code:'query' }"></vxe-toolbar>
				</div>
			</div>
			<div class="d-flex h-100 b-s flex-column">
				<div class="d-flex flex-1">
					<div class="overflow">
						<vxe-table ref="playletTable" key="playletTable" border height="100%" resizable size="medium"
							:loading="tableLoading" :loading-config="{icon: 'vxe-icon-indicator roll', text: '正在拼命加载中...'}"
							:data="dataList">
							<vxe-column width="100" field="id" title="ID" sortable align="center"></vxe-column>
							<vxe-column width="220" field="name" title="短剧名称"  align="center">
								<template  v-slot="{ row }">
									<div >{{row.name}}</div>
									<div  v-if="row.alias_name">
										<div>别名：【{{row.alias_name}}】</div>
									</div>
									<div v-if="row.registration_at" :style="becomeDue(row)">授权书过期时间：{{row.registration_at}}</div>
								</template>
							</vxe-column>
							<vxe-column width="120" field="cover" title="短剧封面图" align="center">
								<template v-slot="{ row }">
									<img class="pointer" width="80" height="auto" :src="row.cover" style="border-radius: 5px;"
										@click.stop="previewPicFn(row.cover,row.name+' 封面图')">
								</template>
							</vxe-column>
							<vxe-column width="120" field="thumbnail" title="短剧缩略图" align="center">
								<template v-slot="{ row }">
									<img class="pointer" width="80" height="auto" :src="row.thumbnail" style="border-radius: 5px;"
										@click.stop="previewPicFn(row.thumbnail,row.name+' 缩略图')">
								</template>
							</vxe-column>
							<vxe-column width="300" field="introduction" title="简介" align="center"></vxe-column>

							<vxe-column width="220" field="playlet_type_name" title="短剧类型" align="center">
								<template v-slot="{ row }">
									<div>{{row.playlet_type_name}}</div>
									<div v-if="row.playlet_type==2">
										<div>【{{row.merge_playlet_name[0]}}】</div>
										<div>【{{row.merge_playlet_name[1]}}】</div>
									</div>
								</template>
							</vxe-column>

							<vxe-column width="150" field="drama_status_name" title="微信剧目审核状态" align="center">
								<template v-slot="{ row }">
									<div>{{row.drama_status_name}}</div>
									<div>{{'剧目ID:'+row.drama_id}}</div>
								</template>
							</vxe-column>
							<vxe-column width="150" field="album_status_name" title="抖音剧目审核状态" align="center">
								<template v-slot="{ row }">
									<div style="display: flex;align-items: center;justify-content: center;">
										{{row.album_status_name}}
										<el-popover
											v-if="row.album_status == 3"
											placement="right"
											width="600"
											trigger="click">
											<el-table :data="diytable" border>
												<!-- <el-table-column width="250" prop="scope_list" label="能力列表"></el-table-column> -->
												<el-table-column width="350" prop="album_msg" label="审核备注"></el-table-column>
											
											</el-table>
											<i @click="diyalbum_status_name(row)" slot="reference" class="el-icon-info"></i>
									
										</el-popover>
										
									</div>
									<div>{{'剧目ID:'+row.album_id}}</div>
									<div>{{row.scope_list}}</div>
								</template>
							</vxe-column>
							<vxe-column width="150" field="playet_episodes_count" title="总共集数" sortable align="center"></vxe-column>
							<vxe-column width="150" field="is_finish_name" title="是否完结" align="center"></vxe-column>
							<vxe-column width="120" field="amount" title="价格(币)" sortable align="center"></vxe-column>
							<vxe-column width="120" field="pay_type_name" title="支付类型" align="center"></vxe-column>
							<vxe-column width="200" field="last_episode_name" title="最后集名称" align="center"></vxe-column>
							<vxe-column width="200" field="pay_start_cid" title="付费起始剧集id" sortable align="center"></vxe-column>
							<vxe-column width="100" field="status_name" title="状态" align="center"></vxe-column>
							<vxe-column width="120" field="likes_number" title="点赞数量" sortable align="center"></vxe-column>
							<vxe-column width="120" field="share_number" title="分享数量" sortable align="center"></vxe-column>
							<vxe-column width="120" field="hot_number" title="热度数量" sortable align="center"></vxe-column>
							<vxe-column width="160" field="created_at" title="创建时间" sortable cell-type="string" align="center"></vxe-column>
							<vxe-column width="160" field="updated_at" title="更新时间" sortable cell-type="string" align="center"></vxe-column>
							<vxe-column v-if="!tableLoading||(dataList.length&&$hasPermissionNum(['playlet:playlet:episodesList','playlet:playlet:batchUpload','playlet:playlet:update','playlet:playlet:delete','playlet:playlet:clickOnline','playlet:playlet:clickOffline','playlet:playlet:limitNumber','playlet:playlet:weComBind','playlet:playlet:registrationTime']))" 
							title="操作" fixed="right" 
							:width="($hasPermissionNum(['playlet:playlet:episodesList','playlet:playlet:batchUpload','playlet:playlet:update','playlet:playlet:delete','playlet:playlet:clickOnline','playlet:playlet:clickOffline','playlet:playlet:limitNumber','playlet:playlet:weComBind','playlet:playlet:registrationTime']))>=4?400:200" 
							align="center" cell-class-name="py-10">
								<template v-slot="{ row }">
									<el-button size="small" round icon="el-icon-video-play"
									v-if="$hasPermission('playlet:playlet:episodesList')"
									@click="lookVideoData(row,'wx_original_url')" type="primary">查看小程序剧集</el-button>
									
									
									<el-button size="small" round icon="el-icon-video-play"
									v-if="$hasPermission('playlet:playlet:episodesList')"
									@click="lookVideoData(row,'play_url')" type="primary">查看剧集</el-button>
									
									
									<el-button size="small" round icon="el-icon-upload2"
									v-if="$hasPermission('playlet:playlet:batchUpload') && row.playlet_type!=2"
									@click="uploadAddData(row,1)" type="primary">批量上传原视频</el-button>
									
									
									<el-button size="small" round icon="el-icon-upload2"
									v-if="$hasPermission('playlet:playlet:batchUpload')  && row.playlet_type!=2"
									@click="uploadAddData(row,2)" type="primary">批量上传压缩视频</el-button>
									
									
									<el-button size="small" round icon="el-icon-edit"
									v-if="$hasPermission('playlet:playlet:update')"
									@click="addOrUpdateData(row)" type="primary">修改</el-button>
									
									<el-button size="small" round icon="el-icon-delete"
									v-if="$hasPermission('playlet:playlet:delete')"
									@click="deleteHandleSetter(row)" type="danger">删除</el-button>
									
									<el-button size="small" round icon="el-icon-s-promotion"
									v-if="$hasPermission('playlet:playlet:clickOnline') && row.is_online==1"
									@click="clickOnline(row)" type="success">剧集上线</el-button>
									<el-button size="small" round icon="el-icon-s-promotion"
									v-if="$hasPermission('playlet:playlet:clickOffline') && row.is_online==0"
									@click="clickOffline(row)" type="warning">剧集下线</el-button>
									
									<el-button size="small" round icon="el-icon-edit"
									v-if="$hasPermission('playlet:playlet:limitNumber')"
									@click="UpdatelimitNumber(row)" type="danger">付费集数</el-button>

									<el-button size="small" round icon="el-icon-edit"
									v-if="$hasPermission('playlet:playlet:weComBind')"
									@click="bindingWeCom(row)" type="primary">绑定企微客服</el-button>

									<el-button size="small" round icon="el-icon-edit"
									v-if="$hasPermission('playlet:playlet:registrationTime')"
									@click="registrationTime(row)" type="primary">授权书过期时间</el-button>
									
								</template>
							</vxe-column>
							<template #empty>
								<div class="d-flex flex-row a-center j-center font-md">
									<div class="d-flex">
										暂时没有数据~
									</div>
								</div>
							</template>
						</vxe-table>
					</div>
				</div>
			</div>
			<!-- 分页 -->
			<div class="d-flex" slot="footer">
				<vxe-pager background size="medium" align="right" :border="false" :current-page="dataForm.page"
					:page-size="dataForm.pageSize" :total="total" :pageSizes="[20,50,100,150,200]"
					:layouts="['PrevPage', 'JumpNumber', 'NextPage', 'Sizes', 'FullJump', 'Total']"
					@page-change="handlePageChange">
				</vxe-pager>
			</div>
			<!-- 新增/修改弹窗 -->
			<playlet-add-or-update v-if="addOrUpdateVisible" ref="addOrUpdateDialog"
			
				@refreshDataList="getTableList"></playlet-add-or-update>

			<!-- 新增/修改弹窗 -->
			<playlet-add-or-update v-if="addOrUpdateVisible2" ref="addOrUpdateDialog2"
			
			@refreshDataList="getTableList"></playlet-add-or-update>
			<!-- 批量上传弹窗 -->
			<upload-add-or-update v-if="uploadAddVisible" ref="uploadAddDialog"></upload-add-or-update>
			<!-- 图片预览弹窗 -->
			<pic-preview v-if="picVisible" ref="picDialog"></pic-preview>
			<!-- 视频预览弹窗 -->
			<video-view v-if="videoVisible" ref="videoDialog"></video-view>
			
			<!-- 付费集数 -->
			<!-- Form -->
			<el-dialog title="付费集数" width="650px" :visible.sync="dialoglimitNumber">
			  <el-form class="limitForm" :model="limi" label-width="150px" size="medium" :inline="false" labelSuffix="：">
			    <el-form-item label="付费集数" size="medium">
			      <el-select v-model="limi.pay_episodes_number" placeholder="请选择剧集">
			        <el-option v-for="(item,index) in allEpisodeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
		
			      </el-select>
			    </el-form-item>
			  </el-form>
			  <div slot="footer" class="dialog-footer">
			    <el-button @click="dialoglimitNumber = false">取 消</el-button>
			    <el-button type="primary" @click="updatalimi">确 定</el-button>
			  </div>
			</el-dialog>


			<el-dialog title="绑定企微客服" width="650px" :visible.sync="dialoglimitNumber2">
			  <el-form class="limitForm" :model="bindWeComId" label-width="150px" size="medium" :inline="false" labelSuffix="：">
			    <el-form-item label="绑定企微客服" size="medium">
			      <el-select v-model="bindWeComId.we_com_id" placeholder="请选择企微客服">
			        <el-option v-for="(item,index) in allWeComList" :key="item.value" :label="item.label" :value="item.value"></el-option>
			      </el-select>
			    </el-form-item>
			  </el-form>
			  <div slot="footer" class="dialog-footer">
			    <el-button @click="dialoglimitNumber2 = false">取 消</el-button>
			    <el-button type="primary" @click="updatalimi2">确 定</el-button>
			  </div>
			</el-dialog>

			<el-dialog title="授权书过期时间" width="650px" :visible.sync="registrationDialog">
			  <el-form class="limitForm" :model="registration" label-width="150px" size="medium" :inline="false" labelSuffix="：">
			    <el-form-item label="授权书过期时间" size="medium">
					<el-date-picker
						v-model="registration.time"
						type="date"
						value-format="yyyy-MM-dd"
						placeholder="选择日期">
					</el-date-picker>
			    </el-form-item>
			  </el-form>
			  <div slot="footer" class="dialog-footer">
			    <el-button @click="registrationDialog = false">取 消</el-button>
			    <el-button type="primary" @click="updataRegistration">确 定</el-button>
			  </div>
			</el-dialog>
		</template>
		
		<template v-else>
			<div class="d-flex a-center j-center h-100 b-s flex-column">
				<img class="d-flex b-s mt-2 mb-10" src="../../../public/image/download.png" alt="没有访问权限" style="width: 300px;">
				<div class="d-flex">抱歉，您没有访问权限</div>
			</div>
		</template>
	</d2-container>
</template>

<script>
	let that;
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import mixinViewModule from '@/mixins/view-module'
	import PlayletAddOrUpdate from './playlet-add-or-update'
	import UploadAddOrUpdate from './upload-add-or-update'
	import VideoView from './video-view'
	import PicPreview from './picPreview'
	export default {
		mixins: [mixinViewModule],
		components: {
			PlayletAddOrUpdate,
			UploadAddOrUpdate,
			PicPreview,
			VideoView
		},
		data() {
			return {
				registrationDialog:false,
				limi: {},
				allEpisodeList:[],
				addOrUpdateVisible2:false,
				dialoglimitNumber:false,
				dialoglimitNumber2:false,
				tableLoading:false,
				click_rowData:{},
				curent: 0,
				total: 0,
				curName: '',
				dataForm: {
					page: 1,
					pageSize: 20,
					keyword:'',//搜索
				},
				playTitle:'',
				innerPlayVisible: false,
				uploadAddVisible: false,//批量上传弹窗
				picVisible: false,
				videoVisible:false,
				// 增改
				addOrUpdateVisible: false,
				roleVisible: false,
				dataList: [],
				diytable:[],
				allWeComList:[],
				bindWeComId:{},
				registration:{
					id:'',
					time:''
				},
			}
		},
		created() {
			if (this.$hasPermission('playlet:playlet:index')) {
				this.getTableList();
			}
		},
		mounted(){
			that = this;
		},
		computed: {
			...mapState('d2admin/user', [
				'info'
			])
			
		},
		methods: {
			...mapMutations({
				pageInit: 'd2admin/page/init',
				headerSet: 'd2admin/menu/headerSet'
			}),
			becomeDue(row){
				let now = Date.now();
				let date = new Date(row.registration_at);
				let timestamp = date.getTime();
				if( (now + 3 * 24 * 60 * 60 * 1000) >= timestamp ){
					return {color:'red'}
				}else{
					return
				}
			
			},
			diyalbum_status_name(row){
				let arr = [];
				arr.push(row)
				this.diytable = arr
				console.log(253,this.diytable)
			},
			//预览图片
			previewPicFn(cover,title) {
				this.picVisible = true;
				this.$nextTick(() => {
					this.$refs.picDialog.update(cover, title);
				})
			},
			clickOnline(row){
				console.log(410,row)
				this.$confirm(this.$t('public.prompt.info', {
					handle: `确认${row.name}剧集上线`
				}), this.$t('public.prompt.title'), {
					confirmButtonText: this.$t('views.public.confirm'),
					cancelButtonText: this.$t('views.public.cancel'),
					type: 'warning'
				}).then(() => {
					console.log(418)
					this.$axios.post(`/api/playlet/playlet/clickOnline/${row.id}`, {})
					.then(res => {
						console.log(419,res)
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 500,
							onClose: () => {
								this.getTableList()
							}
						})
					})
					.catch(() => {})
				}).catch(() => {})
			},
			async registrationTime(row){
		
				this.registrationDialog = true
				const time = await this.$axios.get(`/api/playlet/playlet/registrationTime/${row.id}`)
		
				this.registration.time =  time.registration_at ? time.registration_at : ''
				this.registration.id = time.id
		
			},
			async updataRegistration(){
				console.log(388,this.registration.time)
				const res = await this.$axios.post(`/api/playlet/playlet/registrationTime/${this.registration.id}`,{
					registration_at:this.registration.time
				})
				this.$message({
					message: '修改成功！',
					type: 'success',
					duration: 1200
				})
				this.registrationDialog = false
				this.getTableList()
			},
			clickOffline(row){
				console.log(410,row)
				this.$confirm(this.$t('public.prompt.info', {
					handle: `确认${row.name}剧集下线`
				}), this.$t('public.prompt.title'), {
					confirmButtonText: this.$t('views.public.confirm'),
					cancelButtonText: this.$t('views.public.cancel'),
					type: 'warning'
				}).then(() => {
					console.log(418)
					this.$axios.post(`/api/playlet/playlet/clickOffline/${row.id}`, {})
					.then(res => {
						console.log(419,res)
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 500,
							onClose: () => {
								this.getTableList()
							}
						})
					})
					.catch(() => {})
				}).catch(() => {})
			},
			

			async updatalimi(){
				if(this.limi.pay_episodes_number==''||this.limi.pay_episodes_number==0){
					return this.$message({
								message: '请选择剧集！',
								type: 'error',
								duration: 1200
							})
				}
				const episodeRes = await this.$axios.post(`/api/playlet/playlet/limitNumber/${this.limi.playlet_id}`, {
					pay_episodes_number:this.limi.pay_episodes_number
				});
				this.$message({
					message: '修改成功！',
					type: 'success',
					duration: 1200
				})
				this.dialoglimitNumber = false
			
			},
			async updatalimi2(){
				if(this.bindWeComId.we_com_id==''||this.bindWeComId.we_com_id==0){
					return this.$message({
								message: '请选择企业微信客服！',
								type: 'error',
								duration: 1200
							})
				}
				await this.$axios.post(`/api/playlet/playlet/weComBind/${this.bindWeComId.id}`, {
					we_com_id:this.bindWeComId.we_com_id
				});
				this.$message({
					message: '修改成功！',
					type: 'success',
					duration: 1200
				})
				this.dialoglimitNumber2 = false
			
			},
			async UpdatelimitNumber(row){//付费集数
				const episodeRes = await this.$axios.get(`/api/playlet/playlet/episodes/${row.id}`);
				if(Array.isArray(episodeRes)){
					if(episodeRes.length){
						this.allEpisodeList = episodeRes;
						
					}else{
						this.allEpisodeList = [];
					}
				}
				const diylist = await this.$axios.get(`/api/playlet/playlet/limitNumber/${row.id}`)
				
				diylist.pay_episodes_number==0 ? diylist.pay_episodes_number='' : diylist.pay_episodes_number
				this.limi = diylist
				this.dialoglimitNumber = true
			},

			async bindingWeCom(row){
				
				const WeComList = await this.$axios.get(`/api/common/weCom`);
				if(Array.isArray(WeComList)){
					if(WeComList.length){
						this.allWeComList = WeComList;
						
					}else{
						this.allWeComList = [];
					}
				}

				const bindWeComId = await this.$axios.get(`/api/playlet/playlet/weComBind/${row.id}`)
				bindWeComId.we_com_id==0 ? bindWeComId.we_com_id='' : bindWeComId.we_com_id
				console.log(331,bindWeComId )

				this.bindWeComId = bindWeComId
				this.dialoglimitNumber2 = true

			},

			cellClickFn({row,columnIndex}){
				this.click_rowData = row;
			},
			closeVideoDialogFn() {
				console.log(this.player);
				if (this.player) {
					this.player.pause();
					this.player.seek(0);
				}
			},
			async getTableList(init=false) {
				if(init&&typeof init =='boolean'){
					this.dataForm.page = 1;
				}
				this.tableLoading = true;
				const tableRes = await this.$axios.get('/api/playlet/playlet?'+this.$qs.stringify(this.dataForm))
				tableRes.data.forEach(element => {
					element.merge_playlet_name =  element.merge_playlet_name.split(",")
				});
				this.tableLoading = false;
				this.dataList = tableRes.data;
				this.total = tableRes.total;
			},
			// 查看视频 type wx_original_url小程序  play_url原上传剧集
			async lookVideoData(row,type) {
				console.log(row)
				this.videoVisible = true;
				if (typeof row == 'object' && row != null) {
					// this.curName = row.real_name;
					const id = row.id;
					const videoListRes = await this.$axios.get(`/api/playlet/playlet/episodesList/${id}`, {});
					if(Array.isArray(videoListRes)){
						if(videoListRes.length){
							this.$nextTick(() => {
								this.$refs.videoDialog.typeUrl=type;
								this.$refs.videoDialog.title=row.name;
								this.$refs.videoDialog.update(videoListRes);
							})
							return;
						}
					}
					this.$message({
						message: '剧集视频为空！',
						type: 'error',
						duration: 1200
					})
				}
			},
			//提交审核  key 1微信 2抖音
			async submitDxamine(row,key){
				console.log(row.id);
				this.$confirm('是否提交审核?', '重要提示', {
					confirmButtonText: '确定',
				    cancelButtonText: '取消',
				    type: 'warning'
				}).then(() => {
					this.$axios.get(`/api/playlet/playlet/auditDrama/${row.id}/${key}`, {}).then(res=>{
						this.getTableList();
						console.log(res);
						if(typeof res == 'object' && res!=null){
							if(res.code == 407) return;
						}
						this.$message({
							message: '提交审核成功！',
							type: 'success',
							duration: 1500
						})
					});
				}).catch();
			},
			//新增/修改弹窗
			async addOrUpdateData(row) {
				console.log(428,row)
				this.addOrUpdateVisible = true;
				if (typeof row == 'object' && row != null) {
					// this.curName = row.real_name;
					const id = row.id;
					const userRes = await this.$axios.get(`/api/playlet/playlet/update/${id}`, {});
					console.log(434,userRes)
					this.$nextTick(() => {
						this.$refs.addOrUpdateDialog.playId = id;
						this.$refs.addOrUpdateDialog.merge = false;
						this.$refs.addOrUpdateDialog.innerTitle = row.name;
						this.$refs.addOrUpdateDialog.update(userRes);
					})
				} else {
					this.$nextTick(() => {
						this.$refs.addOrUpdateDialog.playId = null;
						this.$refs.addOrUpdateDialog.merge = false;
						this.$refs.addOrUpdateDialog.init()
					})
				}
			},

			//合并视频
			mergeList(){
				this.addOrUpdateVisible2 = true;
				this.$nextTick(() => {

						this.$refs.addOrUpdateDialog2.playId = null;
						this.$refs.addOrUpdateDialog2.merge = true;
						this.$refs.addOrUpdateDialog2.init()
					})
			},
			//批量上传弹窗
			async uploadAddData(row,type=1) {
				console.log(row)
				this.uploadAddVisible = true;
				if (typeof row == 'object' && row != null) {
					// this.curName = row.real_name;
					const id = row.id;
					const userRes = await this.$axios.get(`/api/playlet/playlet/update/${id}`, {});
					this.$nextTick(() => {
						this.$refs.uploadAddDialog.playId = id;
						this.$refs.uploadAddDialog.innerTitle = row.name;
						this.$refs.uploadAddDialog.dataForm.name = userRes.name;
						this.$refs.uploadAddDialog.init(type);
					})
				}
			},
			// 删除
			deleteHandleSetter(row) {
				this.$confirm(this.$t('public.prompt.info', {
					handle: this.$t('views.public.delete')
				}), this.$t('public.prompt.title'), {
					confirmButtonText: this.$t('views.public.confirm'),
					cancelButtonText: this.$t('views.public.cancel'),
					type: 'warning'
				}).then(() => {
					this.$axios.delete(`/api/playlet/playlet/delete/${row.id}`, {}).then(res => {
						this.$message({
							message: this.$t('views.public.success'),
							type: 'success',
							duration: 500,
							onClose: () => {
								this.getTableList()
							}
						})
					}).catch(() => {})
				}).catch(() => {})
			}
			
			
		}
	}
</script>

<style lang="scss" scoped>
	:deep(.vxe-cell .el-button){
		margin-bottom: 10px;
	}
	.limitForm{
		width: 500px;
	}
	.el-icon-info{
		font-size: 18px;
		margin-left: 5px;
	}
	.el-icon-info:hover{
		color: #409EFF;
		cursor: pointer;
	}
</style>